<script setup>
  import request from "@/utils/request.js";
  import { ref, onMounted, reactive } from "vue";
  import * as echarts from 'echarts';
  import { 
    User, 
    ShoppingCart, 
    Van, 
    Tickets, 
    TrendCharts, 
    Histogram 
  } from '@element-plus/icons-vue';

  const statsData = ref(null);
  const loginLogsData = ref(null);
  const orderStatsData = ref(null);
  const loading = ref(true);
  const chartInstance = ref(null);

  // 加载系统统计数据
  const loadStats = async () => {
    try {
      const res = await request.get("/stats");
      statsData.value = res.data;
    } catch (error) {
      console.error("加载统计数据失败:", error);
    }
  };

  // 加载最近登录日志
  const loadLoginLogs = async () => {
    try {
      const res = await request.get("/loginlog/all/page", {
        params: { pageNum: 1, pageSize: 8 },
      });
      loginLogsData.value = res.data;
    } catch (error) {
      console.error("加载登录日志失败:", error);
    } finally {
      loading.value = false;
    }
  };

  // 加载最近7天订单统计
  const loadRecentOrderStats = async () => {
    try {
      const res = await request.get("/order/stats/recent");
      orderStatsData.value = res.data;
      initChart();
    } catch (error) {
      console.error("加载订单统计数据失败:", error);
    }
  };

  // 初始化图表
  const initChart = () => {
    if (!orderStatsData.value) return;
    
    // 等待DOM渲染完成
    setTimeout(() => {
      const chartDom = document.getElementById('order-chart');
      if (!chartDom) return;
      
      chartInstance.value = echarts.init(chartDom);
      
      const option = {
        title: {
          text: '最近14天订单数量',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '13%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: orderStatsData.value.dates,
          axisLabel: {
            interval: 0, 
            rotate: 45,
            fontSize: 10
          }
        },
        yAxis: {
          type: 'value',
          minInterval: 1
        },
        series: [
          {
            name: '订单数量',
            type: 'bar',
            data: orderStatsData.value.counts,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#2378f7' },
                  { offset: 0.7, color: '#2378f7' },
                  { offset: 1, color: '#83bff6' }
                ])
              }
            }
          }
        ]
      };
      
      chartInstance.value.setOption(option);
    }, 100);
  };

  // 监听窗口大小变化，调整图表大小
  const handleResize = () => {
    if (chartInstance.value) {
      chartInstance.value.resize();
    }
  };

  onMounted(() => {
    loadStats();
    loadLoginLogs();
    loadRecentOrderStats();
    window.addEventListener('resize', handleResize);
  });
</script>

<template>
  <div class="admin-home">
    <h2 class="page-title">系统概览</h2>
    
    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="data-overview">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card user-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">用户账户</div>
              <div class="stat-value">{{ statsData?.userCount || 0 }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card commodity-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><ShoppingCart /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">商品数量</div>
              <div class="stat-value">{{ statsData?.commodityCount || 0 }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card rider-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Van /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">骑手数量</div>
              <div class="stat-value">{{ statsData?.riderCount || 0 }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card order-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Tickets /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">订单数量</div>
              <div class="stat-value">{{ statsData?.orderCount || 0 }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 订单统计和登录记录并排显示 -->
    <el-row :gutter="20" class="data-detail-row">
      <!-- 订单统计图表 -->
      <el-col :span="14">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>订单统计</span>
              <el-icon><TrendCharts /></el-icon>
            </div>
          </template>
          <div id="order-chart" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 最近登录记录 -->
      <el-col :span="10">
        <el-card class="recent-login" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>最近登录记录</span>
              <el-icon><Histogram /></el-icon>
            </div>
          </template>
          <el-table
            v-loading="loading"
            :data="loginLogsData?.list || []"
            style="width: 100%"
            stripe
          >
            <el-table-column prop="username" label="用户名" width="90" />
            <el-table-column prop="nickname" label="昵称" width="90" />
            <el-table-column prop="loginTime" label="登录时间" width="280" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag
                  :type="scope.row.status === 'SUCCESS' ? 'success' : 'danger'"
                  size="small"
                >
                  {{ scope.row.status === 'SUCCESS' ? '成功' : '失败' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.admin-home {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 22px;
  color: #303133;
}

.data-overview {
  margin-bottom: 20px;
}

.data-detail-row {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 15px;
}

.stat-icon .el-icon {
  font-size: 32px;
  color: white;
}

.stat-info {
  flex: 1;
}

.stat-title {
  font-size: 16px;
  color: #606266;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

/* 卡片颜色 */
.user-card .stat-icon {
  background-color: #409EFF;
}

.commodity-card .stat-icon {
  background-color: #67C23A;
}

.rider-card .stat-icon {
  background-color: #E6A23C;
}

.order-card .stat-icon {
  background-color: #F56C6C;
}

/* 图表相关样式 */
.chart-card {
  height: 100%;
}

.chart-container {
  height: 350px;
  width: 100%;
}

.recent-login {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-size: 16px;
  font-weight: bold;
}
</style>